﻿/*
    Copyright Rmlife co.2009 
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;

using Rmlife.Common;
using Rmlife.Config;
using Rmlife.Data;
using Rmlife.Model;
using Rmlife.Control;



namespace Rmlife.Site
{

    /// <summary>
    /// 定义的动作
    /// </summary>
    public struct UserAction
    {
        #region
        /// <summary>
        /// 根据动作ID返回指定的动作名称
        /// </summary>
        /// <param name="actionid">动作ID</param>
        /// <returns></returns>
        public static string GetActionDescriptionByID(int actionid)
        {
            if (actionid == IndexShow.ActionID)
            {
                return IndexShow.ActionDescription;
            }

            if (actionid == Login.ActionID)
            {
                return Login.ActionDescription;
            }

            return "";
        }

        /// <summary>
        /// 通过动作ID得到动作名称
        /// </summary>
        /// <param name="actionid">动作ID</param>
        /// <returns></returns>
        private static string GetActionName(int actionid)
        {
            //从配置文件中读取
            return "";
        }

        /// <summary>
        /// 通过动作ID得到动作描述
        /// </summary>
        /// <param name="actionid">动作描述</param>
        /// <returns></returns>
        private static string GetActionDescription(int actionid)
        {
            //从配置文件中读取
            return "";
        }

        /// <summary>
        /// 首页
        /// </summary>
        public struct IndexShow
        {

            /// <summary>
            /// 动作ID
            /// </summary>
            public static int ActionID
            {
                get
                {
                    return 1;
                }
            }

            /// <summary>
            /// 动作名称
            /// </summary>
            public static string ActionName
            {
                get
                {
                    string m_actionname = GetActionName(ActionID);
                    return m_actionname != "" ? m_actionname : "IndexShow";
                }
            }

            /// <summary>
            /// 动作描述
            /// </summary>
            public static string ActionDescription
            {
                get
                {
                    string m_actiondescription = GetActionDescription(ActionID);
                    return m_actiondescription != "" ? m_actiondescription : "浏览首页";
                }
            }
        }


        /// <summary>
        /// 用户登陆
        /// </summary>
        public struct Login
        {
            /// <summary>
            /// 动作ID
            /// </summary>
            public static int ActionID
            {
                get
                {
                    return 4;
                }
            }

            /// <summary>
            /// 动作名称
            /// </summary>
            public static string ActionName
            {
                get
                {
                    string m_actionname = GetActionName(ActionID);
                    return m_actionname != "" ? m_actionname : "Login";
                }
            }

            /// <summary>
            /// 动作描述
            /// </summary>
            public static string ActionDescription
            {
                get
                {
                    string m_actiondescription = GetActionDescription(ActionID);
                    return m_actiondescription != "" ? m_actiondescription : "网站登陆";
                }
            }
        }

        #endregion
    }

    /// <summary>
    /// 网站工具类
    /// </summary>
    public class WebUtils
    {
        /// <summary>
        /// 验证码生成的取值范围
        /// </summary>
        private static string[] verifycodeRange = { "0","1","2","3","4","5","6","7","8","9"
                                                    //,"a","b","c","d","e","f","g",
                                                    //"h","j","k","m","n",
                                                    //"p","q","r","s","t",
                                                    //"u","v","w","x","y"        
                                                  };
        /// <summary>
        /// 生成验证码所使用的随机数发生器
        /// </summary>
        private static Random verifycodeRandom = new Random();

        /// <summary>
        /// 返回用户密码cookie明文
        /// </summary>
        /// <param name="password">密码密文</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        public static string GetCookiePassword(string password, string key)
        {
            return DES.Decode(password, key);
        }
        /// <summary>
        /// 返回网站用户密码cookie明文
        /// </summary>
        /// <param name="key">密钥</param>
        /// <returns></returns>  
        public static string GetCookiePassword(string key)
        {
            return DES.Decode(GetCookie("password"), key).Trim();

        }

        /// <summary>
        /// 返回密码密文
        /// </summary>
        /// <param name="password">密码明文</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        public static string SetCookiePassword(string password, string key)
        {
            return DES.Encode(password, key);
        }

        #region Cookies

        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">项</param>
        /// <param name="strValue">值</param>
        public static void WriteCookie(string strName, string strValue)
        {
            WriteCookie("user", strName, strValue, 0);
        }
        public static void WriteCookie(string key, string strName, string strValue, int expires)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[CompanyProperties.ASSEMBLY_COOKIEKEY + "_" + key];
            if (cookie == null)
            {
                cookie = new HttpCookie(CompanyProperties.ASSEMBLY_COOKIEKEY + "_" + key);
                cookie.Values[strName] = Utils.UrlEncode(strValue);

                if (expires > 0)
                {
                    cookie.Expires = DateTime.Now.AddMinutes(expires);
                }
            }
            else
            {

                cookie.Values[strName] = Utils.UrlEncode(strValue);
                if (HttpContext.Current.Request.Cookies[CompanyProperties.ASSEMBLY_COOKIEKEY + "_" + key]["expires"] != null)
                {
                    int Xexpires = Utils.StrToInt(HttpContext.Current.Request.Cookies[CompanyProperties.ASSEMBLY_COOKIEKEY + "_" + key]["expires"].ToString(), 0);
                    if (Xexpires > 0)
                    {
                        cookie.Expires = DateTime.Now.AddMinutes(Xexpires);
                        expires = Xexpires;
                    }
                    else
                    {
                        if (expires > 0)
                        {
                            cookie.Expires = DateTime.Now.AddMinutes(expires);
                        }
                    }
                }
                else
                {
                    if (expires > 0)
                    {
                        cookie.Expires = DateTime.Now.AddMinutes(expires);

                    }

                }
            }

            cookie.Values["expires"] = expires.ToString();

            HttpContext.Current.Response.AppendCookie(cookie);
        }

        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="intValue">值</param>
        public static void WriteCookie(string strName, int intValue)
        {
            WriteCookie(strName, intValue.ToString());
        }

        /// <summary>
        /// 登录用户的cookie
        /// </summary>
        /// <param name="uid">用户Id</param>
        /// <param name="expires">cookie有效期</param>
        /// <param name="passwordkey">用户密码Key</param>
        //public static void WriteUserCookie(int uid, int expires, string passwordkey)
        //{
        //    LoginUserInfo info = LoginUsers.GetLoginUserInfo(uid);
        //    WriteUserCookie(info, expires, passwordkey);
        //}
        /// <summary>
        /// 写登录用户的cookie
        /// </summary>
        /// <param name="uid">用户Id</param>
        /// <param name="expires">cookie有效期</param>
        /// <param name="passwordkey">用户密码Key</param>
        //public static void WriteUserCookie(string username, int expires, string passwordkey)
        //{
        //    LoginUserInfo info = LoginUsers.GetLoginUserInfo(username);
        //    WriteUserCookie(info, expires, passwordkey);
        //}

        /// <summary>
        /// 写登录用户的cookie
        /// </summary>
        /// <param name="userinfo">用户信息</param>
        /// <param name="expires">cookie有效期</param>
        /// <param name="passwordkey">用户密码Key</param>
        public static void WriteUserCookie(LoginUserInfo info, int expires, string passwordkey)
        {
            if (info == null)
            {
                return;
            }
            HttpCookie cookie = new HttpCookie(CompanyProperties.ASSEMBLY_COOKIEKEY + "_user");
            cookie.Values["userid"] = info.nID.ToString();
            cookie.Values["password"] = Utils.UrlEncode(SetCookiePassword(info.sLoginPwd, passwordkey));
            cookie.Values["expires"] = expires.ToString();
            if (expires > 0)
            {
                cookie.Expires = DateTime.Now.AddMinutes(expires);
            }

            HttpContext.Current.Response.AppendCookie(cookie);
        }


        /// <summary>
        /// 获得cookie值
        /// </summary>
        /// <param name="strName">项</param>
        /// <returns>值</returns>
        public static string GetCookie(string strName)
        {
            return GetCookie("user", strName);
        }
        public static string GetCookie(string key, string strName)
        {
            if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[CompanyProperties.ASSEMBLY_COOKIEKEY + "_" + key] != null && HttpContext.Current.Request.Cookies[CompanyProperties.ASSEMBLY_COOKIEKEY + "_" + key][strName] != null)
            {
                return Utils.UrlDecode(HttpContext.Current.Request.Cookies[CompanyProperties.ASSEMBLY_COOKIEKEY + "_" + key][strName].ToString());
            }

            return "";
        }

        /// <summary>
        /// 清除登录用户的cookie
        /// </summary>
        public static void ClearUserCookie()
        {
            ClearUserCookie("user");
        }
        public static void ClearUserCookie(string key)
        {
            ClearUserCookieAll(CompanyProperties.ASSEMBLY_COOKIEKEY + "_" + key);
        }

        public static void ClearUserCookieAll(string cookieName)
        {
            HttpCookie cookie = new HttpCookie(cookieName);
            cookie.Values.Clear();
            cookie.Expires = DateTime.Now.AddYears(-1);
            HttpContext.Current.Response.AppendCookie(cookie);
        }

        #endregion

        /// <summary>
        /// 是否为有效域
        /// </summary>
        /// <param name="host">域名</param>
        /// <returns></returns>
        public static bool IsValidDomain(string host)
        {
            Regex r = new Regex(@"^\d+$");
            if (host.IndexOf(".") == -1)
            {
                return false;
            }
            return r.IsMatch(host.Replace(".", string.Empty)) ? false : true;
        }

        /// <summary>
        /// 产生验证码
        /// </summary>
        /// <param name="len">长度</param>
        /// <param name="OnlyNum">是否仅为数字</param>
        /// <returns>string</returns>
        public static string CreateAuthStr(int len, bool OnlyNum)
        {
            int number;
            StringBuilder checkCode = new StringBuilder();

            for (int i = 0; i < len; i++)
            {
                if (!OnlyNum)
                {
                    number = verifycodeRandom.Next(0, verifycodeRange.Length);
                }
                else
                {
                    number = verifycodeRandom.Next(0, 10);
                }
                checkCode.Append(verifycodeRange[number]);
            }

            return checkCode.ToString();
        }

        /// <summary>
        /// 返回用户安全问题答案的存储数据
        /// </summary>
        /// <param name="questionid">问题id</param>
        /// <param name="answer">答案</param>
        /// <returns></returns>
        public static string GetUserSecques(int questionid, string answer)
        {
            if (questionid > 0)
            {
                return Utils.MD5(answer + Utils.MD5(questionid.ToString())).Substring(15, 8);
            }
            return "";
        }

        /// <summary>
        /// 处理列，并绑定数据
        /// </summary>
        /// <param name="gettype"></param>
        /// <param name="_columnTitle"></param>
        /// <param name="_dataField"></param>
        /// <param name="column"></param>
        public static void SetDataColumn(string gettype, string _columnTitle, string _dataField, System.Web.UI.WebControls.BoundColumn column)
        {
            if (column == null)
                return;

            if (!string.IsNullOrEmpty(_columnTitle))
            {
                string Title = string.Empty;
                switch (gettype)
                {
                    case "search":
                        Title = "搜索结果：";
                        break;
                    case "order":
                        Title = "排序结果：";
                        break;
                    default:
                        break;
                }

                System.Web.UI.WebControls.BoundColumn ResultColumn = column;
                ResultColumn.Visible = true;
                ResultColumn.HeaderText = Title + _columnTitle;
                ResultColumn.DataField = _dataField;


            }
        }
        /// <summary>
        /// 处理数据列结果
        /// </summary>
        /// <param name="e"></param>
        /// <param name="col"></param>
        /// <param name="keyword"></param>
        /// <param name="keytype"></param>
        public static void SetDataColumnResult(System.Web.UI.WebControls.DataGridItemEventArgs e, int col, string keyword, string keytype)
        {
            if (!string.IsNullOrEmpty(keyword) && e.Item != null && e.Item.ItemIndex >= 0)
            {
                string str = e.Item.Cells[col].Text;

                // 特殊处理

                Regex r = new Regex(keyword, RegexOptions.IgnoreCase);
                if (r.IsMatch(str))
                {
                    e.Item.Cells[col].Text = r.Replace(str, "<span style=\"background-color:yellow;\">" + keyword + "</span>");
                }
            }
        }

        /*
        /// <summary>
        /// 得到性别:名
        /// </summary>
        /// <param name="gender"></param>
        /// <returns></returns>
        public static string GetGender(string gender)
        {
            return GetGender(DataUtils.GetSexValueByName(gender));
        }
        */
        /*
        /// <summary>
        /// 得到性别:值
        /// </summary>
        /// <param name="gender"></param>
        /// <returns></returns>
        public static string GetGender(int genderValue)
        {
            if (genderValue == DicSex.Male.Value)
                return DicSex.Male.Name;
            else if (genderValue == DicSex.Female.Value)
                return DicSex.Female.Name;
            else
                return DicSex.Unknown.Name;
        }
        */

        /// <summary>
        /// 导出控件数据到EXCEL
        /// </summary>
        /// <param name="eControl"></param>
        public static void ExportDataToExcel(System.Web.UI.WebControls.WebControl eControl)
        {
            ExportDataToExcel(eControl, string.Empty, null);
        }
        public static void ExportDataToExcel(System.Web.UI.WebControls.WebControl eControl, string[] removeColumns)
        {
            ExportDataToExcel(eControl, string.Empty, removeColumns);
        }
        public static void ExportDataToExcel(System.Web.UI.WebControls.WebControl eControl, string filenamePrefix)
        {
            ExportDataToExcel(eControl, filenamePrefix, null);
        }
        /// <summary>
        /// 导出控件数据到EXCEL
        /// </summary>
        /// <param name="eControl"></param>
        public static void ExportDataToExcel(System.Web.UI.WebControls.WebControl eControl, string filenamePrefix, string[] removeColumns)
        {
            #region 预处理数据

            if (eControl is Rmlife.Control.DataGrid)
            {
                Rmlife.Control.DataGrid obj = (Rmlife.Control.DataGrid)eControl;
                if (obj == null) return;

                for (int i = 0; i < obj.Columns.Count; i++)
                {
                    //obj.Columns[i].SortExpression = string.Empty;
                    if (obj.Columns[i].HeaderText == string.Empty)
                    {
                        obj.Columns[i].Visible = false;
                    }
                    //去掉内容中有input的
                    if (obj.Columns[i].HeaderText.IndexOf("<input") > -1)
                    {
                        obj.Columns[i].Visible = false;
                    }

                    if (removeColumns != null)
                    {
                        if (Utils.InArray(i.ToString(), removeColumns))
                        {
                            obj.Columns[i].Visible = false;
                        }
                    }
                }
                eControl = obj;
            }

            #endregion

            string sFileName = filenamePrefix + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";

            string filecontenttype = "application/vnd.ms-excel";
            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.Charset = "UTF-8";
            System.Web.HttpContext.Current.Response.Buffer = true;

            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            System.Web.HttpContext.Current.Response.ContentType = filecontenttype;

            eControl.EnableViewState = false;
            eControl.Attributes.Add("style", "vnd.ms-excel.numberformat:@");

            System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("ZH-CN", false);
            System.IO.StringWriter sw = new System.IO.StringWriter(ci);
            System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
            eControl.RenderControl(htw);


            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + sFileName);

            string sText = sw.ToString();


            // 去掉超链接
            sText = System.Text.RegularExpressions.Regex.Replace(sText, "<a .+?>(.+?)</a>", "$1", System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.IgnoreCase | RegexOptions.Singleline);


            FileStream fs = File.Create(System.Web.HttpContext.Current.Server.MapPath(WebConfigs.Paths.CacheRoot + sFileName));
            StreamWriter ws = new StreamWriter(fs, Encoding.UTF8);
            ws.Write(sText);
            ws.Close();

            System.Web.HttpContext.Current.Response.WriteFile(System.Web.HttpContext.Current.Server.MapPath(WebConfigs.Paths.CacheRoot + sFileName));
            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.Close();

            if (File.Exists(System.Web.HttpContext.Current.Server.MapPath(WebConfigs.Paths.CacheRoot + sFileName)))
            {
                File.SetAttributes(System.Web.HttpContext.Current.Server.MapPath(WebConfigs.Paths.CacheRoot + sFileName), FileAttributes.Normal);
                File.Delete(System.Web.HttpContext.Current.Server.MapPath(WebConfigs.Paths.CacheRoot + sFileName));
            }

            System.Web.HttpContext.Current.Response.End();

        }

        #region GetUserOrVisitor
        /// <summary>
        /// 得到用户或访客的超链接
        /// </summary>
        public static string GetUserOrVisitor(string uid, string cid, string itypeid)
        {
            string ret = "";

            if (uid != null && uid != "")
            {
                if (itypeid == "1") ret = "../CompanyManage/UserShow.aspx?userid=" + uid + "&companyid=" + cid;
                if (itypeid == "2") ret = "../CompanyManage/VisitorShow.aspx?userid=" + uid + "&companyid=" + cid;
            }

            return ret;
        }
        #endregion

        #region GetPageSplitWhere
        /// <summary>
        /// 分页条件判断TextBox
        /// </summary>
        public static string GetPageSplitWhere(Rmlife.Control.TextBox txtwc, string webReq, string keyWhere, ref string _keyword)
        {
            string strWhere = "";

            if (!string.IsNullOrEmpty(txtwc.Text.Trim()))
            {
                if (webReq != "")
                {
                    _keyword = webReq;

                    if (txtwc.Text != webReq)
                    {
                        _keyword = txtwc.Text;
                    }

                    strWhere += " and " + keyWhere + " like '%" + _keyword + "%'";
                }
                else
                {
                    strWhere += " and " + keyWhere + " like '%" + txtwc.Text + "%'";

                }
            }

            return strWhere;
        }

        /// <summary>
        /// 分页条件判断TextBox
        /// </summary>
        public static string GetPageSplitWhere(Rmlife.Control.TextBox txtwc, string webReq, string keyWhere, ref string _keyword, bool isAdmin)
        {
            string strWhere = "";

            if (webReq != "")
            {
                _keyword = webReq;

                if (!string.IsNullOrEmpty(txtwc.Text) && txtwc.Text != webReq)
                {
                    _keyword = txtwc.Text;
                }

                strWhere += " and " + keyWhere + " = " + _keyword;
            }
            else
            {
                if (!string.IsNullOrEmpty(txtwc.Text))
                    strWhere += " and " + keyWhere + " = " + txtwc.Text;

            }


            return strWhere;
        }


        /// <summary>
        /// 分页条件判断DropDownList
        /// </summary>
        public static string GetPageSplitWhere(Rmlife.Control.DropDownList drpList, string webReq, string keyWhere, ref string _keyword)
        {
            string strWhere = "";

            if (drpList.SelectedValue != "")
            {
                if (webReq != "")
                {
                    _keyword = webReq;

                    if (drpList.SelectedValue != webReq)
                    {
                        _keyword = drpList.SelectedValue;
                    }

                    strWhere += " and " + keyWhere + " = '" + _keyword + "'";
                }
                else
                {
                    strWhere += " and " + keyWhere + " = '" + drpList.SelectedValue + "'";

                }
            }

            return strWhere;
        }

        /// <summary>
        /// 分页条件判断Calendar
        /// </summary>
        public static string GetPageSplitWhere(Rmlife.Control.Calendar cldStart, Rmlife.Control.Calendar cldEnd, string webReqStart, string webReqEnd, string keyWhere, ref string _keywordStart, ref string _keywordEnd)
        {
            string strWhere = "";

            if (cldStart.SelectedDate < cldEnd.SelectedDate)
            {
                if (cldStart.SelectedDate != System.Convert.ToDateTime(GetDateDefault()) || cldEnd.SelectedDate != System.Convert.ToDateTime(GetDateDefault()))
                {
                    if (webReqStart != "" || webReqEnd != "")
                    {
                        if (webReqStart != "")
                        {
                            _keywordStart = webReqStart;

                            if (cldStart.SelectedDate.ToShortDateString() != webReqStart)
                            {
                                _keywordStart = cldStart.SelectedDate.ToShortDateString();
                            }

                            strWhere += " and " + keyWhere + ">='" + _keywordStart + "'";
                        }

                        if (webReqEnd != "")
                        {
                            _keywordEnd = webReqEnd;

                            if (cldEnd.SelectedDate.ToShortDateString() != webReqEnd)
                            {
                                _keywordEnd = cldEnd.SelectedDate.AddDays(1).ToShortDateString();
                            }

                            strWhere += " and " + keyWhere + "<='" + _keywordEnd + "'";
                        }

                    }
                    else
                    {
                        if (cldStart.SelectedDate != System.Convert.ToDateTime(GetDateDefault())) strWhere += " and " + keyWhere + ">='" + cldStart.SelectedDate.ToShortDateString() + "'";
                        if (cldEnd.SelectedDate != System.Convert.ToDateTime(GetDateDefault())) strWhere += " and " + keyWhere + "<='" + cldEnd.SelectedDate.AddDays(1).ToShortDateString() + "'";
                    }
                }
            }
            else
            {
                strWhere = "error";
            }

            return strWhere;
        }
        #endregion

        #region 列表自动隐藏
        /// <summary>
        /// 列表自动隐藏
        /// </summary>
        public static bool GetListAutoVisible(Rmlife.Control.DataGrid dgList, System.Web.UI.HtmlControls.HtmlGenericControl divList, PageDataInfo pd)
        {
            bool ret = true;

            if (pd.PageTable == null)
            {
                ret = false;
            }
            else
            {
                if (pd.PageTable.Rows.Count >= 0 || pd.TotalRecord >= 0)
                {
                    divList.Visible = true;
                    dgList.DataSource = pd.PageTable;
                    dgList.DataBind();

                    ret = true;
                }
                else
                {
                    //divList.Visible = false;
                    divList.Visible = true;
                    ret = false;
                }
            }


            return ret;
        }
        #endregion

        #region 日历控件默认值
        public static string GetDateDefault()
        {
            string retDate = "1899-12-30";
            return retDate;
        }

        public static string GetIsDateNull(string strDate)
        {
            string retDate = "";
            if (strDate != GetDateDefault())
                retDate = strDate;
            return retDate;
        }

        #endregion



        #region 日期格式化
        public static string GetDateFormat(string date)
        {
            string ret = "";

            if (!string.IsNullOrEmpty(date))
                ret = DateTime.Parse(date).ToString("yyyy-MM-dd");

            return ret;
        }
        #endregion


    }
}
